import { login, getUserInfo } from '@/api/user'
import md5 from 'md5'
import { setItem, getItem, removeAllItem } from '@/utils/storage'
import { TOKEN } from '@/constant'
import { setTimeStamp } from '@/utils/auth'
const state = {
  token: getItem(TOKEN) || '',
  userInfo: {}
}

const mutations = {
  RECIVE_token(state, token) {
    state.token = token
    setItem(TOKEN, token)
  },
  RECIVE_userInfo(state, userInfo) {
    state.userInfo = userInfo
  }

}

const actions = {
  // 用户登录写法二
  async userLoginRquest({ commit }, data) {
    const { username, password } = data
    return new Promise((resolve, reject) => {
      login({
        username,
        password: md5(password)
      })
        .then(res => {
          console.log(res.data.token)
          commit('RECIVE_token', res.data.token)
          // 保存当前登录时间
          setTimeStamp()

          resolve()
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  async getUserInfoRquest({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then(res => {
          console.log(res.data)
          commit('RECIVE_userInfo', res.data)

          resolve()
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  // 用户主动退出
  logout({ commit }) {
    commit('RECIVE_token', '')
    commit('RECIVE_userInfo', {})
    removeAllItem()
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
